package com.huifeng.servlet;

import com.alibaba.fastjson.JSON;
import com.huifeng.bean.Car;
import com.huifeng.bean.ResultVo;
import com.huifeng.service.CarService;
import com.huifeng.utils.PageUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/car")
public class CarServlet extends BeanServlet {
    //创建service中的方法
    CarService ss=new CarService();
    ResultVo vo=null;
    //分页查询
    public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //首先获取总记录数'
        int count = ss.findtotalcount();
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");
        PageUtils pu=new PageUtils(count,Integer.parseInt(pageSize),currentPage);
        List<Car> list = ss.selectByPage(pu);
        //存域
        pu.setList(list);
        //在实际运行过程中,我们需要给他存一个集合
        //创建一个对象,响应给用户数据
        vo=new ResultVo(200,"查询成功",pu);
        //将对象转换为json 传到前端页面
        String s = JSON.toJSONString(vo);
        //响应给前端
        resp.getWriter().print(s);
    }
    public void insertCar(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        //在这里我们实现添加工作
        Map<String, String[]> map = req.getParameterMap();
        //创建一个Car对象
        Car car=new Car();
        //调用方法进行自动结合
        BeanUtils.populate(car,map);
        //调用底层的添加方法
        int row = ss.insertCar(car);
        //添加判断
        if(row>0){
            vo= new ResultVo(200,"添加汽车成功",row);
        }else{
            vo= new ResultVo(500,"添加汽车失败",row);
        }
        //将该值转json
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);
    }
}
